package br.edu.intec.agenda.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import br.edu.intec.agenda.exception.DAOException;

public class ConnectionFactory {
	
	private static final String JDBC_DRIVER = "org.postgresql.Driver";
	private static final String URL = "jdbc:postgresql://localhost:5432/agenda";
	private static final String USER = "patrick";
	private static final String PASSW = "postgres";

	public static Connection getConnection() throws DAOException{
		
		try {
		    Class.forName(JDBC_DRIVER);
            return DriverManager.getConnection(URL, USER, PASSW);
		} catch (Exception e) {
            throw new DAOException("Servidor Fora do ar, tente mais tarde! ");
        }
	}
	
	public static void closeConnection(Connection conn) throws DAOException {
	        close(conn, null, null);
	}

    public static void closeConnection(Connection conn, 
                                       PreparedStatement pstm) throws DAOException {
        close(conn, pstm, null);
    }

    public static void closeConnection(Connection conn, 
                                       PreparedStatement pstm, 
                                       ResultSet rs) throws DAOException {
        close(conn, pstm, rs);
    }

    private static void close(Connection conn, 
                              PreparedStatement pstm, 
                              ResultSet rs) throws DAOException {
        try {
            if (rs != null) rs.close();
            if (pstm != null) pstm.close();
            if (conn != null) conn.close();
        } catch (Exception e) {
            throw new DAOException("Conexão caiu, volte mais tarde!");
        }
    }
}
